package com.wnhz.work.jy.activity;

import android.Manifest;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wnhz.work.jy.BaseActivity;
import com.wnhz.work.jy.MyApplication;
import com.wnhz.work.jy.MyMain;
import com.wnhz.work.jy.R;
import com.wnhz.work.jy.fragment.LoginFragment;
import com.wnhz.work.jy.fragment.SignFragment;
import com.wnhz.work.jy.utils.ConfigUtil;
import com.wnhz.work.jy.utils.xutils3.MyCallBack;
import com.wnhz.work.jy.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ---登录注册
 */
public class LoginActivity extends BaseActivity implements View.OnClickListener {
    private TextView tv_sign, tv_login;
    private ImageView iv_img1, iv_img2;

    private LoginFragment fragment1;
    private SignFragment fragment2;

    private List<Fragment> fragmentList;
    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private IWXAPI api;

    private String from;

    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 111;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 845;

    private ImageView iv_top;
    private String pic;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    ImageLoader.getInstance().displayImage(pic, iv_top);
                    break;

                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        initData();
        initView();
    }

    private void initData() {
        from = getIntent().getStringExtra("from");
    }

    private void initView() {
        findViewById(R.id.rl_back).setOnClickListener(this);
        findViewById(R.id.rl_sign).setOnClickListener(this);
        findViewById(R.id.rl_login).setOnClickListener(this);

        tv_sign = (TextView) findViewById(R.id.tv_sign);
        tv_login = (TextView) findViewById(R.id.tv_login);
        iv_img1 = (ImageView) findViewById(R.id.iv_img1);
        iv_img2 = (ImageView) findViewById(R.id.iv_img2);

        iv_top = (ImageView) findViewById(R.id.iv_top);

        fragmentList = new ArrayList<>();
        fragment1 = new LoginFragment();
        fragment2 = new SignFragment();

        fragmentList.add(fragment1);
        fragmentList.add(fragment2);

        fragmentManager = getFragmentManager();
        transaction = fragmentManager.beginTransaction();
        transaction.add(R.id.fl_content, fragment1);
        transaction.add(R.id.fl_content, fragment2);

        transaction.hide(fragment2);

        transaction.commit();

        showDialog();
        uploadByxUtils();


    }

    private void uploadByxUtils() {

        XUtil.Post(ConfigUtil.LOGINPIC, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                System.out.println(result + "sssssssssssssss");
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    pic = jsonObject.optString("pic");

                    if ("1".equals(res)) {
                        mHandler.sendEmptyMessage(1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!MyApplication.getInstance().is_start_login){
            closeDialog();
        }

    }

    private void hideFragment() {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        for (int i = 0; i < fragmentList.size(); i++) {
            transaction.hide(fragmentList.get(i));
        }
        transaction.commit();
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        hideFragment();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        switch (v.getId()) {
            //返回
            case R.id.rl_back:
                if ("fragment5".equals(from)) {
                    intent = new Intent(this, MyMain.class);
                    intent.putExtra("Pagination", 0);
                    startActivity(intent);
                } else if ("fragment4".equals(from)) {
                    intent = new Intent(this, MyMain.class);
                    intent.putExtra("Pagination", 2);
                    startActivity(intent);
                }
                finish();
                break;

            //登录
            case R.id.rl_login:
                closrKeyboard();
                transaction.show(fragmentList.get(1)).commit();
                tv_sign.setTextColor(0x80ffffff);
                tv_login.setTextColor(0xffffffff);
                iv_img1.setVisibility(View.INVISIBLE);
                iv_img2.setVisibility(View.VISIBLE);
                break;

            //注册
            case R.id.rl_sign:
                closrKeyboard();
                transaction.show(fragmentList.get(0)).commit();
                tv_sign.setTextColor(0xffffffff);
                tv_login.setTextColor(0x80ffffff);
                iv_img1.setVisibility(View.VISIBLE);
                iv_img2.setVisibility(View.INVISIBLE);
                break;

            default:
                break;
        }
    }


    public void agreement() {
        Intent intent = new Intent(this, WebActivity.class);
        intent.putExtra("url", ConfigUtil.HEADER + "agreement");
        intent.putExtra("title", "服务协议");
        startActivity(intent);
    }

    public void weixinLoading() {
        api = WXAPIFactory.createWXAPI(this, "wx054406f5ccd828da", true);
        api.registerApp("wx054406f5ccd828da");
    }

    public void scanCode() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    MY_PERMISSIONS_REQUEST_CALL_PHONE);
        } else {
            startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                startActivityForResult(new Intent(this, CaptureActivity.class), REQUEST_CODE);
            } else {
                MyToast("很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。");
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    Log.e(TAG, "onActivityResult: " + result);
                    String s = "pid/";

                    if (result.indexOf(s) > 0) {
                        String pId = result.substring(result.indexOf(s) + s.length(), result.length());
                        Log.e(TAG, "onActivityResult: " + pId);
                        getInviteCode(pId);
                    }

                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(this, "无效的二维码", Toast.LENGTH_LONG).show();
                }
            }
        }
    }

    private static final String TAG = "LoginActivity";

    private void getInviteCode(String pId) {
        Map<String, Object> map = new HashMap<>();
        map.put("pId", pId);
        showDialog();
        XUtil.Post(ConfigUtil.GETINVITECODE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e(TAG, "onSuccess: " + result);
                try {
                    String inviteCode = new JSONObject(result).optString("inviteCode");
                    fragment2.setet_invitation(inviteCode);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
                Log.e(TAG, "onFinished: ");
                closeDialog();
            }
        });
    }

}
